package com.tools.permissions.library;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import androidx.annotation.Size;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.tools.permissions.library.easypermissions.EasyPermissions;


public class DOPermissions   {
    public interface DOPermissionsCallbacks extends EasyPermissions.PermissionCallbacks {

    }

    private static DOPermissions instance;
    private WeakReference<FragmentActivity> mActivity;
    private WeakReference<Fragment> mFragment;

    private DOPermissions() {
    }

    public static synchronized DOPermissions getInstance() {
        if (null == instance) {
            instance = new DOPermissions();
        }
        return instance;
    }

    /**
     * 获取权限
     *
     * @param fragment    当前Fragment
     * @param rationale   提示
     * @param requestCode 返回的code
     * @param perms       授权失败的列表
     */
    public void getPermissions(@NonNull Fragment fragment, @NonNull String rationale,
                               int requestCode, @Size(min = 1) @NonNull String... perms) {
        if (mFragment != null) {
            if (mFragment.get() != null) {
                mFragment.clear();
            }
        }
        mFragment = new WeakReference<>(fragment);
        EasyPermissions.requestPermissions(
                mFragment.get(),
                rationale,
                requestCode,
                perms);
    }

    /**
     * 获取权限
     *
     * @param act         当前Activity
     * @param rationale   提示
     * @param requestCode 返回的code
     * @param perms       授权失败的列表
     */
    public void getPermissions(@NonNull FragmentActivity act, @NonNull String rationale, int requestCode,  @Size(min = 1) @NonNull String... perms) {
        if (mActivity != null) {
            if (mActivity.get() != null) {
                mActivity.clear();
            }
        }
        mActivity = new WeakReference<>(act);
        EasyPermissions.requestPermissions(
                mActivity.get(),
                rationale,
                requestCode,
                perms);
    }

    /**
     * Activity或Fragment需要重写onRequestPermissionsResult()方法，把执行操作给这个方法
     */
    public void setRequestPermission(Object o,int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, o);
    }


    /**
     * 检查权限是否存在
     *
     * @param context 上下文
     * @param perms   权限列表
     */
    public boolean hasPermission(@NonNull Context context, @Size(min = 1) @NonNull String... perms) {
        return EasyPermissions.hasPermissions(context, perms);
    }
}
